package com.example.p001_interview01;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 实现一个容器，提供两个方法，add，size，写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 *
 * @param <T>
 */
public class MonitorContainter02<T> {

    private List<T> c = new ArrayList<>();

    public synchronized void add(T t) {
        c.add(t);
    }

    public synchronized int size() {
        return c.size();
    }

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {

        MonitorContainter02 m = new MonitorContainter02();

        t1 = new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                m.add(Thread.currentThread().getName() + i);
                System.out.println(Thread.currentThread().getName() + " 添加第" + i + "个元素");

                if (m.size() == 5) {
                    LockSupport.unpark(t2);
                    LockSupport.park();
                }
            }
        });

        t2 = new Thread(() -> {
            LockSupport.park();

            System.out.println(Thread.currentThread().getName() + " 第5个元素");

            LockSupport.unpark(t1);
        });

        t1.start();
        t2.start();

    }


}
